import hashlib
import os
import time
import uuid

from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import path
from hot import models

from hot.forms.bootstrapform import BootStrapForm
from hot.utils.encry import md5_string
from django.utils.safestring import mark_safe
from hot.forms import index
from hot.views.base import BaseCurd


class Index(BaseCurd):
    table_header = ['ID', '小标题', '内容', '图片', '栏目', '状态', '操作']
    table_field = [("db", "count"), ("db", "price")]

    form_class = index.ContentForm

    def get_priority_nums(self):
        category = models.Category.objects.filter(category_name='首页').first()
        nums = range(1, category.priority_num + 1)
        return nums

    def get_instance(self, request, nid):
        return models.ContentManage.objects.filter(id=nid).first()

    def do_delete(self, request, index_id , cid):
        obj = models.ContentManage.objects.filter(content_id=index_id , content_category=cid).first()

        for img_instance in obj.content_imgs.all():
            try:
                img_path = os.path.join(settings.MEDIA_ROOT, img_instance.content_img.name)
                os.remove(img_path)
                print(f"Image file {img_path} deleted successfully.")
            except FileNotFoundError:
                print(f"Image file {img_path} not found.")
            except Exception as e:
                print(f"Error deleting image file {img_path}: {e}")

        obj.delete()

    def get_extra_url(self, obj):
        res = [
            path(f'delete_all/<int:cid>/', self.dispatch(getattr(obj, 'delete_all')), name=f"{obj.prefix}_delete_all"),
            path(f'active/', self.dispatch(getattr(obj, 'active')), name=f"{obj.prefix}_active"),
        ]
        return res

    def get_queryset(self, request, cid, nid=None):
        if nid is None:
            return models.ContentManage.objects.filter(content_category=cid).all()
        print(cid)
        return models.ContentManage.objects.filter(content_priority=nid, content_category=cid).all()

    def delete_all(self, request , cid):
        """删除全部"""
        lst = request.POST.getlist('selected_ids[]')
        for i in lst:
            obj = models.ContentManage.objects.filter(content_id=i).first()
            for img_instance in obj.content_imgs.all():
                try:
                    img_path = os.path.join(settings.MEDIA_ROOT, img_instance.content_img.name)
                    os.remove(img_path)
                    print(f"Image file {img_path} deleted successfully.")
                except FileNotFoundError:
                    print(f"Image file {img_path} not found.")
                except Exception as e:
                    print(f"Error deleting image file {img_path}: {e}")
            obj.delete()

        return JsonResponse({'status': '200', 'data': 'ok'})

    def get_category(self , cid):
        return models.Category.objects.filter(id=cid).first()

    def active(self, request):
        index_id = int(request.POST.get('index_id'))
        active = int(request.POST.get('active'))
        models.ContentManage.objects.filter(content_id=index_id).update(active=active)
        return JsonResponse({'status': '200', 'data': 'ok'})
